﻿using System;
using System.Linq;
using System.Windows;
using HappyBa.Core;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;
using HappyBa.Core.Statistics;
using LightInject;
using Mnk.Library.Common.Log;

namespace HappyBa.Pages
{
    /// <summary>
    /// Interaction logic for StatisticsPage.xaml
    /// </summary>
    public partial class StatisticsPage
    {
        private readonly ILog log = LogManager.GetLogger<StatisticsPage>();
        private IDataCache dataCache;
        private Config config;
        private IStatisticsFacade statisticsFacade;
        private readonly IServiceContainer container;

        public StatisticsPage()
        {
            InitializeComponent();
            container = ((MainWindow)Application.Current.MainWindow).Container;
            container.GetInstance<IDataCollector>().OnDataChanged += (o, e) => OnDataContextChanged(o, new DependencyPropertyChangedEventArgs());
            DataContextChanged += OnDataContextChanged;
        }

        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            dataCache = container.GetInstance<IDataCache>();
            config = container.GetInstance<Config>();
            if (config.Current==null)return;
            
            statisticsFacade = container.GetInstance<IStatisticsFacade>();

            try
            {
                var search = new MetricsSearch(config.Current.Search);
                var metrics = new Metrics(dataCache.Metrics.Data, search);
                var context = new StatisticsContext
                {
                    Metrics = metrics, 
                    ActiveEmployees = config.Current.ActiveEmployees.Select(x => x.Key).ToArray(),
                };
                Results.Text = string.Join(Environment.NewLine, statisticsFacade.Calculate(context));
            }
            catch (Exception ex)
            {
                log.Write(ex, "Can't calculate statistics");
            }
        }

        private void CalculateClick(object sender, RoutedEventArgs e)
        {
            OnDataContextChanged(sender, new DependencyPropertyChangedEventArgs());
        }
    }
}
